﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Net;
using CoursePack;
using HtmlAgilityPack;

namespace WindowsFormsApplication2.Forms
{
    public partial class frmRegister : Form
    {

        List<CourseDescription> list = new List<CourseDescription>();
        public frmRegister()
        {
            InitializeComponent();
        }



        private void frmRegister_Load(object sender, EventArgs e)
        {
            // Load Semester combo box
            this.cmbCurrentSession.Items.Add(ESession.Summer);
            this.cmbCurrentSession.Items.Add(ESession.Winter);
            this.cmbCurrentSession.Items.Add(ESession.Summer);

            
            System.IO.StreamReader file = new System.IO.StreamReader(@"dep.txt");

            University concordia = new University();
            List<string> strs = new List<string>();
            string line;

            while ((line = file.ReadLine()) != null)
            {

                strs.Add(line);
            }

            bool done = false;
            bool flag = false;
            int j = 0;

            while (done == false)
            {
                CoursePack.Faculty f;
                CoursePack.Department d;

                string[] tab = strs[j].Split(';');

                if (tab[0].Length < 3 && tab.Length > 1)
                {
                    f = new Faculty(new University(),int.Parse(tab[0]), tab[1]);
                    concordia.AddFaculty(f);

                    while (flag == false && j + 1 != strs.Count)
                    {

                        string[] tab1 = strs[++j].Split(';');


                        if (tab1[0].Length > 2)
                        {
                            d = new Department(int.Parse(tab1[0]), tab1[1],f);
                            f.addDepartment(d);
                        }
                        else
                            break;
                    }

                }
                else
                    j++;

                if (j == strs.Count)
                    done = true;
            }

            foreach (Faculty f in concordia.Faculties)
            {
                this.cmbPrograms.Items.Add(f);

                foreach (Department d in f.Departments)
                {
                    this.cmbPrograms.Items.Add(d);
                }
            }
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            Type o = this.cmbPrograms.SelectedItem.GetType();
            // Validation of the fields
            if ((this.txtFirstName.Text == "") ||
                (this.txtLastName.Text == "") ||
                (this.txtNetName.Text == "") ||
                (this.txtPassword.Text == "") ||
                (this.txtPasswordConf.Text == "") ||
                (this.cmbPrograms.SelectedItem == null)|| o.FullName != typeof(Department).FullName)
            {
                this.lblStatus.Text = " Please verify the form. Some information are missing !";
            }
            else
            {
                //Verify NetName and Password
                if (VerifyUserLoginInfo())
                {

                    Department program = (Department)this.cmbPrograms.SelectedItem;
                    
                    //Create the student object with the provided information in the form
                    Student student = new Student(this.txtFirstName.Text, this.txtLastName.Text, this.txtNetName.Text, this.txtPassword.Text, program, EnumDegree.SOFT);

                     
                    //program,int.Parse(this.txtCurrentYear.Text),(Session)this.cmbCurrentSession.SelectedItem);
                    foreach (CourseDescription c in list)
                    {
                        student.AddCompleteddCourse(c);
                    }

                    //Serialize the student object to be able to retrieve it uppon the student next login
                    Stream stream = File.Open("Student.osl", FileMode.Create);
                    BinaryFormatter bformatter = new BinaryFormatter();

                    bformatter.Serialize(stream, student);
                    stream.Close();
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }

            }
           

        }

        bool VerifyUserLoginInfo()
        {
            if (this.txtPassword.Text != this.txtPasswordConf.Text)
            {
                this.lblStatus.Text = "Your passwords don't match."; 
                return false;
            }
            
            // First request, we login to MyConcordia Portal
            HttpRequest MyConcordiaLogin = new HttpRequest(HttpMethod.POST, new Uri("https://my.concordia.ca/psp/portprod/?cmd=login&languageCd=ENG"),
                "https://www.myconcordia.ca/",
                "my.concordia.ca",
                new CookieContainer());


            // Get the response from MyConcordia Server
            // If the user authenticate, open the schedule form, otherwise show him failure
            MyConcordiaLogin.SendRequest("userid=" + this.txtNetName.Text + "&pwd=" + this.txtPassword.Text + "&GO=Sign+in&httpPort=&timezoneOffset=300&portal_pwd=" + this.txtPassword.Text);


            if (MyConcordiaLogin.ResponseStream.Contains("are invalid"))
            {
                this.lblStatus.Text = "Your NetName and/or your password are invalid";
                return false;
            }
            else
                return true;
            
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();

        }

        private void vistaButton1_Click(object sender, EventArgs e)
        {
           
            
        }

        private void txtPasswordConf_Leave(object sender, EventArgs e)
        {
            if (this.dataGridView1.RowCount == 0)
            {
                // First request, we login to MyConcordia Portal
                HttpRequest MyConcordiaLogin = new HttpRequest(HttpMethod.POST, new Uri("https://my.concordia.ca/psp/portprod/?cmd=login&languageCd=ENG"),
                    "https://www.myconcordia.ca/",
                    "my.concordia.ca",
                    new CookieContainer());

                MyConcordiaLogin.SendRequest("userid=" + this.txtNetName.Text + "&pwd=" + this.txtPassword.Text+ "&GO=Sign+in&httpPort=&timezoneOffset=300&portal_pwd=" + this.txtPassword.Text);


                HttpRequest Audit = new HttpRequest(HttpMethod.GET, new Uri("https://my.concordia.ca/psc/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_FACULTY_INFO.FieldFormula.IScript_DegNavigator?PORTALPARAM_PTCNAV=CU_DEG_NAVIGATOR&EOPP.SCNode=EMPL&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=CU_DEGREE_AUDIT&EOPP.SCLabel=Degree%20Audit&EOPP.SCPTfname=CU_DEGREE_AUDIT&FolderPath=PORTAL_ROOT_OBJECT.CU_ACADEMIC.CU_DEGREE_AUDIT.CU_DEG_NAVIGATOR&IsFolder=false&PortalActualURL=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2fEMPLOYEE%2fEMPL%2fs%2fWEBLIB_CONCORD.CU_FACULTY_INFO.FieldFormula.IScript_DegNavigator&PortalContentURL=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2fEMPLOYEE%2fEMPL%2fs%2fWEBLIB_CONCORD.CU_FACULTY_INFO.FieldFormula.IScript_DegNavigator&PortalContentProvider=EMPL&PortalCRefLabel=Degree%20Audit&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fmy.concordia.ca%2fpsp%2fportprod%2f&PortalURI=https%3a%2f%2fmy.concordia.ca%2fpsc%2fportprod%2f&PortalHostNode=EMPL&NoCrumbs=yes"),
                "https://my.concordia.ca/psp/portprod/EMPLOYEE/EMPL/s/WEBLIB_CONCORD.CU_FACULTY_INFO.FieldFormula.IScript_DegNavigator?PORTALPARAM_PTCNAV=CU_DEG_NAVIGATOR&EOPP.SCNode=EMPL&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=CU_DEGREE_AUDIT&EOPP.SCLabel=Degree%20Audit&EOPP.SCPTfname=CU_DEGREE_AUDIT&FolderPath=PORTAL_ROOT_OBJECT.CU_ACADEMIC.CU_DEGREE_AUDIT.CU_DEG_NAVIGATOR&IsFolder=false",
                "my.concordia.ca",
                MyConcordiaLogin.Cookies);


                Audit.SendRequest();

                HttpRequest Transcript = new HttpRequest(HttpMethod.GET, new Uri("https://advise2.concordia.ca/DN/Transcript.aspx?pageid=mytranscript"),
                "https://advise2.concordia.ca/Home.aspx?pageid=default",
                "advise2.concordia.ca",
                Audit.Cookies);


                Transcript.SendRequest();

                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                htmlDoc.OptionFixNestedTags = true;
                
                htmlDoc.LoadHtml(Transcript.ResponseStream);

                
                foreach (HtmlNode input in htmlDoc.DocumentNode.SelectNodes("//tbody//tr"))
                {
                    if (input.Attributes.Count > 0)
                        if (input.Attributes[0].Value == "DeAcDataGridItemB")
                        {
                            CourseDescription course;
                            string courseName = "", courseNumber = "", Grade = "";
                            string credits = "0.0";


                            string[] filter = Tools.filterCourse(input.ChildNodes[3].InnerText);
                            courseName = filter[0];
                            courseNumber = filter[1];

                            Grade = input.ChildNodes[7].InnerText;

                            credits = input.ChildNodes[5].InnerText;

                            
                            course = new CourseDescription(courseName, courseNumber, "", credits,"","",CourseStatus.Completed);
                            course.Grade = Grade;
                            list.Add(course);
                        }
                }

                DataTable dttable = new DataTable();

                DataColumn column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "Course";
                dttable.Columns.Add(column);

                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "Credits";
                dttable.Columns.Add(column);

                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "Grade";
                dttable.Columns.Add(column);



                foreach (CourseDescription cc in list)
                {
                    DataRow row = dttable.NewRow();

                    row["Credits"] = cc.Credits;
                    row["Course"] = cc.CourseName + " " + cc.CourseNumber;
                    row["Grade"] = cc.Grade;

                    dttable.Rows.Add(row);
                }


                this.dataGridView1.DataSource = dttable;
            }
        }

        private void txtPassword_TextChanged(object sender, EventArgs e)
        {

        }
        
    }
}
